package com.checkbox.widgetset.client.conn;

import com.google.gwt.user.client.ui.Widget;

import com.checkbox.widgetset.SelectableTreeNode;
import com.checkbox.widgetset.client.share.SelectableTreeNodeState;
import com.checkbox.widgetset.client.ui.VSelectableTreeNode;
import com.checkbox.widgetset.client.ui.VSelectableTreeNode.SelectListener;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ConnectorHierarchyChangeEvent;
import com.vaadin.client.communication.RpcProxy;
import com.vaadin.client.communication.StateChangeEvent;
import com.vaadin.client.ui.AbstractComponentContainerConnector;
import com.vaadin.shared.ui.Connect;

import java.util.LinkedList;
import java.util.List;

@SuppressWarnings("serial")
@Connect(SelectableTreeNode.class)
public class SelectableTreeNodeConnector extends AbstractComponentContainerConnector implements
    SelectListener {
  protected final SelectableTreeNodeServerRpc serverRpc = RpcProxy.create(
      SelectableTreeNodeServerRpc.class, this);

  @Override
  protected void init() {
    super.init();
    getWidget().addSelectListener(this);
  }

  @Override
  public void updateCaption(ComponentConnector connector) {
  }

  @Override
  public void onConnectorHierarchyChange(ConnectorHierarchyChangeEvent connectorHierarchyChangeEvent) {
    List<Widget> widgets = new LinkedList<Widget>();
    for (ComponentConnector connector : this.getChildComponents()) {
      widgets.add(connector.getWidget());
    }
    getWidget().reconstruct(widgets);
  }

  @Override
  public VSelectableTreeNode getWidget() {
    return (VSelectableTreeNode) super.getWidget();
  }

  @Override
  public SelectableTreeNodeState getState() {
    return (SelectableTreeNodeState) super.getState();
  }

  @Override
  public void onStateChanged(StateChangeEvent event) {
    super.onStateChanged(event);
    getWidget().updateFromState(getState());
  }

  @Override
  public void onSelectableTreeNodeSelected(VSelectableTreeNode node, boolean isSelected) {
    serverRpc.onSelected(isSelected);
  }
}
